import router from '../router'
import store from '../store'

const whiteList = ['/login']

router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem('token')
  if (!!token) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      if (store.state.user.routes?.length > 0) {
        next()
      } else {
        try {
          store.commit('user/set_token', token)
          const accessRoutes = await store.dispatch('user/createRoutes')
          // router.addRoutes(accessRoutes)
          accessRoutes.forEach(route => {
            router.addRoute(route)
          })
          router.addRoute({
            path: '*',
            redirect: '/404'
          })
          next({ ...to, replace: true })
        } catch (err) {
          console.log(err)
          next(`/login?redirect=${to.path}`)
        }
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
    }
  }
})